package com.ruoyi.framework.web.service;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.ToolUtil;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service("smsUserDetailsServiceImpl")
public class SmsUserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {
        SysUser user = userService.selectUserByPhone(phone);
        if (ToolUtil.isEmpty(user)) {
            log.info("注册用户手机号：{} 不存在，添加用户", phone);
            //添加用户跟角色
        }
        //校验用户是否有注册用户角色
        //else if (!permissionService.getRolePermission(user).contains(RoleConstants.REGISTER_USER)) {
        //添加用户角色
        //}
        else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", user.getUserName());
            throw new ServiceException("对不起，您的账号：" + user.getUserName() + " 已被删除");
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", user.getUserName());
            throw new ServiceException("对不起，您的账号：" + user.getUserName() + " 已停用");
        }
        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user) {
        //user.setIsPwd(ToolUtil.isNotEmpty(user.getPassword()));//判断密码是否为空
        //获取小程序用户数据
        return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user), permissionService.getRolePermission(user));
    }
}
